package com.hbsd.paopaobackend.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbsd.paopaobackend.common.BaseResponse;
import com.hbsd.paopaobackend.common.ErrorCode;
import com.hbsd.paopaobackend.common.ResultUtils;
import com.hbsd.paopaobackend.exception.BusinessException;
import com.hbsd.paopaobackend.model.domain.User;
import com.hbsd.paopaobackend.model.request.PageInfo;
import com.hbsd.paopaobackend.model.vo.Friend.FriendListVO;
import com.hbsd.paopaobackend.model.vo.UserVO;
import com.hbsd.paopaobackend.service.FriendService;
import com.hbsd.paopaobackend.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Api(tags = "好友模块")
@RestController
@RequestMapping("/friend")
// 配置跨域 allowCredentials: 允许携带cookie
@CrossOrigin(origins = {"http://localhost:5173"}, allowCredentials = "true")

public class FriendController {

    @Resource
    private UserService userService;

    @Resource
    private FriendService friendService;


    /**
     * 获取好友列表
     * @param pageInfo
     * @param request
     * @return
     */
    @ApiOperation(value = "获取好友列表", notes = "获取好友列表 listFriendPage")
    @PostMapping("/list/page")
    public BaseResponse<Page<FriendListVO>> listFriendPage(PageInfo pageInfo, HttpServletRequest request) {
        if(pageInfo == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页参数不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        if(loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
        }

        Page<FriendListVO> friendListPage = friendService.listFriendPage(pageInfo, loginUser);
        return ResultUtils.success(friendListPage);
    }

    @GetMapping("/detail/{userId}")
    public BaseResponse<UserVO> getFriendDetail(@PathVariable("userId") Long userId, HttpServletRequest request) {
        if(userId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户id不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        if(loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "用户未登录");
        }

        User userInfo = userService.getById(userId);
        UserVO friend = userService.changeTagsToArray(userInfo);

        if(friend == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        return ResultUtils.success(friend);
    }
}
